#include <assert.h>

#include "SimpleIo.h"
#include "FieldInfo.h"
#include "ConstantPool.h"
#include "AttributeInfo.h"

#include "Log.h"

FieldInfo::FieldInfo(ConstantPool * cp, FILE * f)
{
  constantPool=cp;

  long int at;
  at=ftell(f);

  u2 acount;
  access_flags=readUint16(f);

  name_index=readUint16(f);
  assert(cp->isUtf8At(name_index));

  signature_index=readUint16(f);
  assert(cp->isUtf8At(signature_index));

  LOG_LOAD("At %ld loading field '%s'\n",at,cp->getCString(name_index));

  acount=readUint16(f);
  for(u2 i;i<acount;i++) 
    attributes.push_back(AttributeInfoFactory::fromFile(cp,f));
}

void FieldInfo::dump(ConstantPool * cp)
{
  printf("Name: '");
  cp->getAt(name_index)->dump(cp);
  printf("' | Signature: '");
  cp->getAt(signature_index)->dump(cp);
  printf("'\n");
}

void FieldInfo::save(FILE *f)
{
  LOG_SAVE("At %ld saving field '%s'\n",ftell(f),constantPool->getCString(name_index));
  writeUint16(f,access_flags);
  writeUint16(f,name_index);
  writeUint16(f,signature_index);
  writeUint16(f,attributes.size());
  for(u2 i=0;i<attributes.size();i++)
    attributes[i]->save(f,constantPool);

}
